package tablet.module_user.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.lib.app.ARouterPathUtils;
import com.lib.app.CodeUtil;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.db.shared_prefrences.interfaces.UserCacheInterface;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.share.tool.StringUtil;
import com.lib.fastkit.views.circle_image.niv.NiceImageView;
import com.lib.fastkit.views.dialog.normal.CoachAIStudyDialog;
import com.lib.fastkit.views.dialog.zenhui.AlertDialog;
import com.lib.http.call_back.HttpDialogCallBack;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.ui.fragment.BaseAppFragment;
import com.lib.utls.glide.GlideConfig;
import com.lihang.ShadowLayout;
import com.umeng.analytics.MobclickAgent;

import butterknife.BindView;
import butterknife.OnClick;
import tablet.module_user.R;
import tablet.module_user.R2;
import tablet.module_user.bean.LoginOutBean;
import tablet.module_user.bean.UserInfoBean;

/**
 * Created by Administrator on 2020/7/13 0013.
 */

public class UserInfoFragment extends BaseAppFragment {


    @BindView(R2.id.iv_user)
    NiceImageView ivUser;

    @BindView(R2.id.lin_name)
    LinearLayout linName;
    @BindView(R2.id.tv_name)
    TextView tvName;
    @BindView(R2.id.tv_school)
    TextView tvSchool;

    @BindView(R2.id.lin_ainum)
    LinearLayout linAINum;
    @BindView(R2.id.tv_num)
    TextView tvAINum;

    @BindView(R2.id.lin_zanflower)
    LinearLayout linZanflower;
    @BindView(R2.id.tv_zan)
    TextView tvZan;
    @BindView(R2.id.tv_flower)
    TextView tvFlower;

    @BindView(R2.id.lin_class)
    LinearLayout linClass;
    @BindView(R2.id.lin_ask)
    LinearLayout linAsk;
    @BindView(R2.id.lin_order)
    LinearLayout linOrder;
    @BindView(R2.id.lin_message)
    LinearLayout linMessage;
    @BindView(R2.id.lin_setting)
    LinearLayout linSetting;
    @BindView(R2.id.lin_logout)
    LinearLayout linLogout;

    @BindView(R2.id.sl_oto)
    ShadowLayout slOto;
    @BindView(R2.id.sl_class)
    ShadowLayout slClass;
    @BindView(R2.id.sl_search)
    ShadowLayout slSearch;
    @BindView(R2.id.sl_sharecircle)
    ShadowLayout slSharecircle;
    @BindView(R2.id.sl_question)
    ShadowLayout slQuestion;
    @BindView(R2.id.sl_jianke)
    ShadowLayout slJianke;

    UserInfoBean.ObjBean userInfoBean;


    @Override
    protected void onCreateView(View view, Bundle savedInstanceState) {

        if ("1".equals(SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserIdentity())) {
            linLogout.setVisibility(View.VISIBLE);
            linZanflower.setVisibility(View.GONE);
            linAINum.setVisibility(View.GONE);
        } else {
            linLogout.setVisibility(View.GONE);
        }
        getUserInfo();


    }

    private void getUserInfo() {

        HttpUtils.with(getActivity())
                .addParam("requestType", "UNIFIED_INTERFACE")
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .execute(new HttpNormalCallBack<UserInfoBean>() {
                    @Override
                    public void onSuccess(UserInfoBean result) {

                        if (result.getCode() == CodeUtil.CODE_200) {
                            if (result.getObj() != null) {

                                userInfoBean = result.getObj();

                                UserCacheInterface userCacheInterface = SharedPreferenceManager.getInstance(getActivity()).getUserCache();
                                //保存是否为平台老师
                                userCacheInterface.setPlatform_teacher(result.getObj().getPersonal_info().getPlatform_teacher());

                                initUserView();

                                //设置剩余AI辅导次数
                                if (result.getObj().getSurplus_classes() > -1) {
                                    tvAINum.setText(result.getObj().getSurplus_classes() + "次");
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }

    private void initUserView() {

        if (userInfoBean != null) {

            UserInfoBean.ObjBean.PersonalInfoBean personalInfoBean = userInfoBean.getPersonal_info();
            if (StringUtil.isNotEmpty(personalInfoBean.getPhoto_url(), true)) {
                Glide.with(getActivity())
                        .load(personalInfoBean.getPhoto_url())
                        .apply(GlideConfig.getCircleOptions())
                        .into(ivUser);
            }

            if (StringUtil.isNotEmpty(personalInfoBean.getName(), true)) {
                tvName.setText(personalInfoBean.getName());
            }

            if (StringUtil.isNotEmpty(personalInfoBean.getTotal() + "", true)) {
                tvSchool.setText(personalInfoBean.getTotal() + "");
            }

            if (StringUtil.isNotEmpty(personalInfoBean.getIdentity() + "", true)) {
                if (1 == personalInfoBean.getIdentity()) {
                    linLogout.setVisibility(View.VISIBLE);
                } else if (1 == personalInfoBean.getIdentity()) {
                    linLogout.setVisibility(View.GONE);
                }
            }

            //点赞和鲜花数量
            if (personalInfoBean.getLike_total() > -1) {
                tvZan.setText(personalInfoBean.getLike_total() + "");
            }
            if (personalInfoBean.getRed_flower() > -1) {
                tvFlower.setText(personalInfoBean.getRed_flower() + "");
            }


        }

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_userinfo;
    }

    @OnClick({R2.id.lin_name, R2.id.lin_class, R2.id.lin_ask, R2.id.lin_order, R2.id.lin_message, R2.id.lin_setting, R2.id.lin_logout,
            R2.id.sl_oto, R2.id.sl_class, R2.id.sl_search, R2.id.sl_sharecircle, R2.id.sl_question, R2.id.sl_jianke})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.lin_name) {

            showNick();

        } else if (i == R.id.lin_class) {

            showToast("该功能正在建设中，敬请期待");
        } else if (i == R.id.lin_ask) {

            ARouter.getInstance().build(ARouterPathUtils.Dayi_AskQuestionActivity).navigation();
        } else if (i == R.id.lin_order) {

            ARouter.getInstance().build(ARouterPathUtils.Tablet_User_OrderListActivity).navigation();

        } else if (i == R.id.lin_message) {

            ARouter.getInstance().build(ARouterPathUtils.User_MessageActivity).navigation();

        } else if (i == R.id.lin_setting) {

            ARouter.getInstance().build(ARouterPathUtils.User_SetActivity).navigation();
        } else if (i == R.id.lin_logout) {

            //退出登录
            CoachAIStudyDialog.getInstance()
                    .setTitle("退出登录")
                    .setContent("你确认要退出登录么?")
                    .setCancelListener(new CoachAIStudyDialog.CancelListener() {
                        @Override
                        public void onCancel() {

                        }
                    })
                    .setSureListener(new CoachAIStudyDialog.SurelListener() {
                        @Override
                        public void onSure() {
                            requestLoginOut();
                        }
                    })
                    .show(getChildFragmentManager());

        } else if (i == R.id.sl_oto) {

            showToast("该功能正在建设中，敬请期待");
        } else if (i == R.id.sl_class) {

            showToast("该功能正在建设中，敬请期待");
        } else if (i == R.id.sl_search) {

//            String url = "http://192.168.0.114:8848/activity.html#/questions/281";
            ARouter.getInstance().build(ARouterPathUtils.Tablet_App_NormalDetailWebActivity)
                    .withString("urlPath", userInfoBean.getArticle_search_url()).navigation();
//            ARouter.getInstance().build(ARouterPathUtils.Tablet_App_NormalDetailWebActivity)
//                    .withString("urlPath", url).navigation();


        } else if (i == R.id.sl_sharecircle) {

//            String url = "http://192.168.0.113:8848/flat.html#/mall";
//            ARouter.getInstance().build(ARouterPathUtils.Tablet_App_NormalDetailWebActivity)
//                    .withString("urlPath", url).navigation();

            showToast("该功能正在建设中，敬请期待");

        } else if (i == R.id.sl_question) {

            ARouter.getInstance().build(ARouterPathUtils.Tablet_App_NormalDetailWebActivity)
                    .withString("urlPath", userInfoBean.getKnowledge_enhancement().getAnswer_interest_url()).navigation();

        } else if (i == R.id.sl_jianke) {

            ARouter.getInstance().build(ARouterPathUtils.Tablet_JianKe_JianKeListActivity).navigation();
        }
    }


    private void requestLoginOut() {

        String token = SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken();

        HttpUtils.with(getActivity())
                .addParam("requestType", "SIGNOUT")
                .addParam("token", token)
                .execute(new HttpDialogCallBack<LoginOutBean>() {
                    @Override
                    public void onSuccess(LoginOutBean result) {

                        if (result.getCode() == CodeUtil.CODE_200) {

                            //ARouter.getInstance().build(ARouterPathUtils.App_MainActivity).navigation();
                            SharedPreferenceManager.getInstance(getActivity()).getUserCache().setUserToken("");
                            SharedPreferenceManager.getInstance(getActivity()).getUserCache().setUserIdentity("");
                            SharedPreferenceManager.getInstance(getActivity()).getUserCache().setPlatform_teacher(0);

                            //退出登录成功之后绑定到友盟登出用户统计中
                            MobclickAgent.onProfileSignOff();
                            //跳转到登录进行重新登录
                            ARouter.getInstance().build(ARouterPathUtils.Tablet_User_LoginActivity).navigation();
                        }
                        getActivity().finish();
                        showToast(result.getMsg());

                    }

                    @Override
                    public void onError(String e) {
                        getActivity().finish();
                    }
                });

    }

    NickNameFragment nickNameFragment;

    private void showNick() {

        final AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setContentView(R.layout.dialog_nick)
                .setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (nickNameFragment != null) {
                            getActivity().getSupportFragmentManager().beginTransaction().remove(nickNameFragment).commit();
                            nickNameFragment = null;
                        }
                    }
                }).fullWidth()
                .addDefaultAnimation()
                .show();

        nickNameFragment = (NickNameFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment_nick);

        nickNameFragment.setOnNomalChangeListener(new NickNameFragment.NormalChangeListener() {
            @Override
            public void onNomalChange(String str) {

                if (StringUtil.isNotEmpty(str, true)) {

                    dialog.dismiss();

                    //将修改的昵称发送到服务器
                    sendChangeNameToService(str);

                } else {
                    showToast("请输入您想要修改的昵称！");
                }
            }
        });
    }

    private void sendChangeNameToService(final String str) {

        HttpUtils.with(getActivity())
                .addParam("requestType", "CHANGE_NAME")
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .addParam("name", str)
                .execute(new HttpDialogCallBack<LoginOutBean>() {
                    @Override
                    public void onSuccess(LoginOutBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {

                            showToast("昵称修改成功！");
                            tvName.setText(str);

                            UserCacheInterface userCacheInterface = SharedPreferenceManager.getInstance(getActivity()).getUserCache();
                            userCacheInterface.setUserName(str);
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });


    }
}
